package view.chart;

import java.awt.Color;
import java.awt.Graphics2D;

/**
 *
 * @author Dennis Nijssen
 */
public class BarChart extends Chart {
    private final int padding;
    
    public BarChart(ChartValue[] values, int padding) {
        super(values);
        
        this.padding = padding;
    }
    
    public BarChart(int padding) {
        this(null, padding);
    }
    
    @Override
    protected void paintChart(Graphics2D g2d) {
        ChartValue[] bars = getValues();
                
        if(bars == null || bars.length == 0) 
            return;
        
        int w = getWidth();
        int h = getHeight();
        
        // Draw vertical line
        g2d.drawLine(padding, padding, padding, (h - padding));
        
        // Draw horizontal line
        g2d.drawLine(padding, (h - padding), (w - padding), (h - padding)); 
        
        // Get highest value
        int highest = 0;
        for(int i = 0; i < bars.length; i++) {
            if(bars[i].getValue() > highest) 
                highest = bars[i].getValue();
        }
        
        // Get value of 1 pixel
        double pixel = (double)highest / ((h - (2 * padding) - 4)); // -4 Because the label above each bar
        
        // Calculate bar width
        int barWidth;
        if(bars.length >= 7) 
            barWidth = ((w - (3 * padding)) - (bars.length * padding)) / bars.length;
        else 
            barWidth = ((w - (10 * padding)) / 7);
        
        // Draw each bar
        int x = 2 * padding;
        int barHeight;
        for(int i = 0; i < bars.length; i++) {            
            // Draw bar with color
            barHeight = (int)(bars[i].getValue() / pixel);
            g2d.setColor(bars[i].getColor());
            g2d.fillRect(x, ((h - padding) - barHeight), barWidth, barHeight);
            
            // Write label above each bar
            g2d.setColor(Color.black);
            g2d.drawString(bars[i].getLabel(), x, ((h - padding) - barHeight - 4));
            
            x += barWidth + padding;
        }
    }
}
